package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.dto.ReservationPageDto;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.CountByTimeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * 预约信息Service业务层处理
 *
 * @author I:P Masquerenaʚїɞ
 * @date 2025-06-09
 */
@Service
@RequiredArgsConstructor
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {

    private final ReservationMapper reservationMapper;

    @Override
    public Integer getCancelledReservationCount() {
        return Db.lambdaQuery(Reservation.class)
                .eq(Reservation::getCreateBy, UserThreadLocal.get())
                .eq(Reservation::getStatus, 2)
                .ge(Reservation::getUpdateTime, LocalDate.now().atStartOfDay())
                .le(Reservation::getUpdateTime, LocalDate.now().plusDays(1).atStartOfDay())
                .count()
                .intValue();
    }

    @Override
    public List<CountByTimeVo> countByTime(Long time) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(time),
                ZoneId.of("Asia/Shanghai")
        );
        return reservationMapper.countByTime(dateTime, dateTime.plusDays(1));
    }

    @Override
    public void saveReservation(ReservationDto reservationDto) {
        Reservation reservation = BeanUtil.copyProperties(reservationDto, Reservation.class);
        reservation.setStatus(0);
        reservation.setCreateBy(UserThreadLocal.getUserId().toString());
        save(reservation);
    }

    @Override
    public List<Reservation> reservationPage(ReservationPageDto reservationDto) {
        return Db.lambdaQuery(Reservation.class)
                .eq(Reservation::getCreateBy, UserThreadLocal.get())
                .eq(reservationDto.getStatus() != null, Reservation::getStatus, reservationDto.getStatus())
                .list();
    }

    @Override
    public void cancelReservation(Long id) {
        Db.lambdaUpdate(Reservation.class)
                .eq(Reservation::getId, id)
                .set(Reservation::getStatus, 2)
                .set(Reservation::getUpdateTime, LocalDateTime.now())
                .update();
    }
}
